package it.lupo.repository.dao;

import it.lupo.model.User;
import it.lupo.repository.HibernateSessionFactory;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BaseDAO<E,I extends Serializable> {
	
	private static Logger log = LoggerFactory.getLogger(BaseDAO.class);
	
	private Class<E> clazz;
	
	public BaseDAO(Class<E> c)
	{
		this.clazz=c;
	}
	
	public Session getSession() {
		return HibernateSessionFactory.getSession();
	}
	
	public void create(E transientInstance) {
		log.debug("saving Style instance");
		try {
			getSession().save(transientInstance);
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}

	public E update(E detachedInstance) {
		log.debug("merging "+clazz.getName()+" instance");
		try {
			E result = (E) getSession().merge(detachedInstance);
			log.debug("update successful");
			return result;
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}

	public void delete(E persistentInstance) {
		log.debug("deleting "+clazz.getName()+" instance");
		try {
			getSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public E findById(I id) {
		log.debug("getting "+clazz.getName()+" instance with id: " + id);
		try {
			E instance = (E) getSession().get(clazz, id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

//	public List<User> findByExample(User instance) {
//		log.debug("finding Style instance by example");
//		try {
//			List<User> results = (List<User>) getSession()
//					.createCriteria(User.class)
//					.add(create(instance)).list();
//			log.debug("find by example successful, result size: "
//					+ results.size());
//			return results;
//		} catch (RuntimeException re) {
//			log.error("find by example failed", re);
//			throw re;
//		}
//	}

	public List<User> findAll() {
		log.debug("finding all "+clazz.getName()+" instances");
		try {
			String queryString = "SELECT entity FROM "+clazz.getName()+" entity";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
}
